<?php
namespace App\Http\Controllers;
use App\Third\WXBizDataCrypt;
use App\User;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Cache;

class LoginController extends Controller {

    public function __construct(Request $request) {

    }

    // code 换取 session_key 强制获取用户信息进行二次保存
    public function getSessionKey(Request $request) {
        $code = $request->input('code', '');
        if ($code) {
            $data = [
                'query' => [
                    'appid' => config('xcx.appid'),
                    'secret' => config('xcx.secret'),
                    'js_code' => $code,
                    'grant_type' => 'authorization_code'
                ]
            ];

            $res = $this->sendGuzzleRequest(config('xcx.jscode2session'), $data, 'get');
//            $res = $this->sendRequest("https://api.weixin.qq.com/sns/jscode2session?appid=wx6aaef9edf974a564&secret=857d2a8269106d14bf76ab249b7d9114&js_code=$code&grant_type=authorization_code", '', Null,'GET');
            if (isset($res->errcode)) {
                // 获取失败 返回错误信息
                info('微信openid获取失败：'.date('y-m-d h:i:s' ,time()).'###############'.$res->errmsg);
                return $this->output(400, $res->errmsg);
            } else {
                // 获取成功 生成唯一token存入cache 保存openid,session_key
                $token = sha1($res->session_key.time()*10000+rand(0,10000));
                Cache::pull($token.'openid');
                Cache::pull($token.'sessionkey');
                Cache::add($token.'openid', $res->openid, 116);
                Cache::add($token.'sessionkey', $res->session_key, 116);
                $user = User::where('openid', $res->openid)->first();
                if (!$user) {
                    // 用户不存在 进行数据库插入保存
                    $user = new User();
                    $user->openid = $res->openid;
                    $user->save();
                    return $this->output(201, '获取成功保存信息', $token);
                } else {
                    // if ($user->avatarurl) {
                    //     return $this->output(200, '获取成功', $token);
                    // } else {
                    //     return $this->output(201, '获取成功保存信息', $token);
                    // }
                    // 当token失效时进行信息重新获取，并更新昵称头像
                    return $this->output(201, '获取成功保存信息', $token);
                }
            }
        } else {
            return $this->output(401, 'code获取失败');
        }
    }

    // code 换取 session_key 不进行用户信息获取 unionid存在直接存储 不存在则用户主动获取时存储
    public function getSessionKeyNoinfo(Request $request) {
        $code = $request->input('code', '');
        if ($code) {
            $data = [
                'query' => [
                    'appid' => config('xcx.appid'),
                    'secret' => config('xcx.secret'),
                    'js_code' => $code,
                    'grant_type' => 'authorization_code'
                ]
            ];
            // 发送 get 请求
            $res = $this->sendGuzzleRequest(config('xcx.jscode2session'), $data, 'get');
            if (isset($res->errcode)) {
                // 获取失败 返回错误信息
                info('微信openid获取失败：'.date('y-m-d h:i:s' ,time()).'###############'.$res->errmsg);
                return $this->output(400, $res->errmsg);
            } else {
                // 获取成功 生成唯一token存入cache 保存openid,session_key
                $token = sha1($res->session_key.time()*10000+rand(0,10000));
                Cache::pull($token.'openid');
                Cache::pull($token.'sessionkey');
                Cache::add($token.'openid', $res->openid, 116);
                Cache::add($token.'sessionkey', $res->session_key, 116);
                $user = User::where('openid', $res->openid)->first();
                if (!$user) {
                    // 用户不存在 进行数据库插入保存
                    $user = new User();
                    $user->openid = $res->openid;
//                    $user->type = $type;
//                    if (isset($res->unionid)) {
//                        $user->unionid = $res->unionid;
//                    }
                    $user->save();
                }
                return $this->output(200, '获取成功保存信息', $token);
            }
        } else {
            return $this->output(401, 'code获取失败');
        }
    }

    // 保存用户详细信息
    public function saveInfo(Request $request) {
        $token = $request->input('token', '');
        $iv = $request->input('iv', '');
        $encryptedData  = $request->input('encryptedData', '');
        $appid = config('xcx.appid');
        if ($token && $iv && $encryptedData) {
            $pc = new WXBizDataCrypt();
            $data = '';
            $back = $pc->decryptData($appid, Cache::get($token.'sessionkey'), $encryptedData, $iv, $data);
            if ($back[0] >= 0) {
                $userinfo = json_decode($back[1]);
                $user = User::where('openid', $userinfo->openId)->first();
                $hashids = new Hashids(env('APP_KEY', 'JfMdiJeoEcrAiKsY60EldxLkGcI2gF9i'), 10);
                $id = $hashids->encode($user->id);
                $user->coding_id = 'us'.$id;
                $user->nickname = $userinfo->nickName;
//                $user->unionid = $userinfo->unionId;
                $user->avatarurl = $userinfo->avatarUrl;
                $user->gender = $userinfo->gender;
                $user->province = $userinfo->province;
                $user->city = $userinfo->city;
                $user->country = $userinfo->country;
                $user->language = $userinfo->language;
                $user->save();
                return $this->output(200, '信息保存成功');
            } else {
                return $this->output(201, '解码失败', $back);
            }
        } else {
            return $this->output(401, '参数错误');
        }
    }
}
